#include "cds_list.h"
#include<stdlib.h>
#include<stdio.h>

struct data {
    struct list_head entry;
    unsigned long data;
};

int main(void){
    
    struct list_head * datas = malloc(sizeof(struct list_head));
    //初始化表头
    INIT_LIST_HEAD(datas); 
    
    //循环添加5个元素
    for(int i=0;i<5;i++){
        struct data * pdata = malloc(sizeof(struct data));
        pdata->data = 100+i;
        list_add(&pdata->entry, datas); 
    }
    
    printf("遍历打印链表中的元素:\n");
    struct list_head * pos;
    list_for_each(pos, datas){
        struct data * ppd = list_entry(pos,struct data, entry);
        printf("ppd->data=%lu\n",ppd->data);
    }

    printf("获取首元素: %lu\n",list_entry(list_first(datas), struct data, entry)->data);
    printf("获取尾元素: %lu\n",list_entry(list_last(datas), struct data, entry)->data);

    printf("头部添加一个元素88后遍历:\n");
    struct data * hdata = malloc(sizeof(struct data));
    hdata->data = 88;
    list_add_head(&hdata->entry, datas );
    list_for_each(pos, datas){
        struct data * ppd = list_entry(pos,struct data, entry);
        printf("ppd->data=%lu\n",ppd->data);
    }
    
    printf("删除88这个节点后遍历:\n");
    list_del(&hdata->entry);
    list_for_each(pos, datas){
        struct data * ppd = list_entry(pos,struct data, entry);
        printf("ppd->data=%lu\n",ppd->data);
    }
    
    struct data * last = list_entry(list_del_last(datas),struct data, entry);
    printf("删除尾部节点:%lu后遍历:\n",last->data);
    list_for_each(pos, datas){
        struct data * ppd = list_entry(pos,struct data, entry);
        printf("ppd->data=%lu\n",ppd->data);
    }
    struct data * first = list_entry(list_del_first(datas), struct data, entry);
    printf("删除头部节点%lu后遍历:\n",first->data);
    list_for_each(pos, datas){
        struct data * ppd = list_entry(pos,struct data, entry);
        printf("ppd->data=%lu\n",ppd->data);
    }

    while(!list_is_empty(datas)){
        struct data * dptr = list_entry(list_del_first(datas), struct data, entry ); 
        printf("删除元素:%lu\n",dptr->data);
    }

    printf("清空链表后遍历:\n");
    list_for_each(pos, datas){
        struct data * ppd = list_entry(pos,struct data, entry);
        printf("ppd->data=%lu\n",ppd->data);
    }
    return 0;
}
